<?php

namespace common\search;

use common\models\IcoProject;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\IcoOrder;
use yii\helpers\ArrayHelper;

/**
 * IcoOrderSearch represents the model behind the search form about `common\models\IcoOrder`.
 */
class IcoOrderSearch extends IcoOrder
{
    public $project_name;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'ico_project_id', 'count', 'status', 'created_at', 'updated_at', 'send_address_time'], 'integer'],
            [['trade_no', 'return_trade_no', 'recieve_address','project_name'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = IcoOrder::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query->orderBy([
                'id' => SORT_DESC
            ]),
        ]);
        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'uid' => $this->uid,
            'ico_project_id' => $this->ico_project_id,
            'count' => $this->count,
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'send_address_time' => $this->send_address_time,
        ]);
        if($this->project_name){
            $pids = IcoProject::find()->where(['like','name',$this->project_name])->select('id')->asArray()->all();
            $pids = ArrayHelper::getColumn($pids,'id');
            if(!empty($pids)){
                $query->andFilterWhere(['in','ico_project_id',$pids]);
            }
            else{
                $query->andWhere('0=1');
            }
        }
        $query->andFilterWhere(['like', 'trade_no', $this->trade_no])
            ->andFilterWhere(['like', 'return_trade_no', $this->return_trade_no])
            ->andFilterWhere(['like', 'recieve_address', $this->recieve_address]);
        return $dataProvider;
    }
}
